"""
Python wrapper for the eval_excute DLL.
This module provides access to C functions for code execution.
"""

import os
import sys
import ctypes
import tempfile
import subprocess
from ctypes import c_char_p, c_void_p, POINTER, Structure, c_int, CDLL

# 根目录
BASE_DIR = os.path.dirname(os.path.abspath(__file__))

# 简化的可用搜索路径
LIB_DIR = os.path.join(BASE_DIR, 'lib')
CODE_EVAL_DIR = os.path.join(BASE_DIR, 'code_eval')

# 可执行文件路径
EVAL_EXCUTE_EXE = os.path.join(CODE_EVAL_DIR, 'eval_excute.exe')
if not os.path.exists(EVAL_EXCUTE_EXE):
    EVAL_EXCUTE_EXE = os.path.join(LIB_DIR, 'eval_excute.exe')

# DLL路径
if sys.platform == 'win32':
    DLL_PATH = os.path.join(LIB_DIR, 'eval_code2.dll')
else:
    DLL_PATH = os.path.join(LIB_DIR, 'libeval_excute.so')

# 加载DLL
eval_lib = None
try:
    if os.path.exists(DLL_PATH):
        if sys.platform == 'win32':
            eval_lib = ctypes.WinDLL(DLL_PATH)
        else:
            eval_lib = CDLL(DLL_PATH)
        
        # 设置函数签名
        eval_lib.get_eval_result.argtypes = [c_char_p]
        eval_lib.get_eval_result.restype = c_void_p
        
        eval_lib.free_result.argtypes = [c_void_p]
        eval_lib.free_result.restype = None
        
        print(f"成功加载代码执行库: {DLL_PATH}")
except Exception as e:
    print(f"加载代码执行库失败: {e}")

def execute_code(code):
    """
    执行C代码并返回结果
    首先尝试使用DLL，如果失败则使用eval_test.exe
    
    参数:
        code (str): 要执行的C代码字符串
        
    返回:
        str: 执行结果
    """
    print(f"开始执行代码...")
    print(f"EVAL_EXCUTE_EXE路径: {EVAL_EXCUTE_EXE}")
    print(f"exe文件存在: {os.path.exists(EVAL_EXCUTE_EXE)}")
    
    if not os.path.exists(EVAL_EXCUTE_EXE):
        error_msg = f"找不到eval_excute.exe: {EVAL_EXCUTE_EXE}"
        print(error_msg)
        raise FileNotFoundError(error_msg)
    
    try:
        # 创建临时文件保存代码
        with tempfile.NamedTemporaryFile(suffix='.c', delete=False, mode='w') as temp_file:
            temp_file_path = temp_file.name
            temp_file.write(code)
        
        # 获取exe所在目录，确保依赖的DLL能被找到
        exe_dir = os.path.dirname(EVAL_EXCUTE_EXE)
        exe_name = os.path.basename(EVAL_EXCUTE_EXE)
        
        print(f"exe目录: {exe_dir}")
        print(f"exe名称: {exe_name}")
        print(f"临时文件: {temp_file_path}")
        print(f"exe目录存在: {os.path.exists(exe_dir)}")
        print(f"exe在目录中存在: {os.path.exists(os.path.join(exe_dir, exe_name))}")
        
        # 使用绝对路径调用exe，不设置工作目录
        print(f"准备执行命令: {EVAL_EXCUTE_EXE} {temp_file_path}")
        result = subprocess.run([EVAL_EXCUTE_EXE, temp_file_path], 
                              capture_output=True, text=True)
        
        print(f"命令执行完成，返回码: {result.returncode}")
        
        # 删除临时文件
        try:
            os.unlink(temp_file_path)
        except:
            pass
        
        if result.returncode == 0:
            # 直接返回stdout输出，不做额外处理
            return result.stdout
        else:
            print(f"执行失败: {result.stderr}")
            return None
            
    except Exception as e:
        print(f"执行代码时出错: {e}")
        return None

# 测试代码
if __name__ == "__main__":
    test_code = """
        int main(){
            int b = 2;
            printf("the number is %d\n", b);
        }
    """
    
    result = execute_code(test_code)
    print("执行结果:")
    print(result) 